from flask import Blueprint, jsonify, request

from app.common.log_utils import logger, with_timing
from app.mod_trade.api.uni_api import batch_buy, batch_sell, batch_cancel, batch_query

bp_trade = Blueprint('trade', __name__)


@bp_trade.route('/trade', methods=['POST'])
@with_timing
def post_trade():
    data = request.get_json(force=True)
    action = data['action']
    security = data.get('security', '')
    if action == 'buy':
        price = data['price']
        logger.info(f'receive {action} {security} price={price}')
        ret = batch_buy(security, price, data['lines'])
    elif action == 'sell':
        price = data['price']
        logger.info(f'receive {action} {security} price={price}')
        ret = batch_sell(security, price, data['lines'])
    elif action == 'cancel':
        logger.info(f'receive {action} {security}')
        ret = batch_cancel(security, data['lines'])
    elif action == 'query':
        category = data['category']
        logger.info(f'receive {action} {security} cat={category}')
        ret = batch_query(category, data['accounts'])
    else:
        return jsonify({'error': f'action not support', 'success': False}), 400

    logger.info(ret)
    return jsonify(ret)
